package com.shengde.jinwawaforleader.model.homePage;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.base.CommonBaseAdapter;
import com.shengde.jinwawaforleader.base.ViewHolder;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.model.myJob.instance_message.Constant;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.BasexUtilsProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProCertificate;
import com.shengde.jinwawaforleader.network.protocolbean.ProShowClickGood;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadImg;
import com.shengde.jinwawaforleader.utils.LGImgCompressor;
import com.shengde.jinwawaforleader.views.SelectPicPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by JYQ on 2017/1/9 0009.
 */
public class EditTeacherMienActivity extends BaseActivity implements AdapterView.OnItemClickListener, LGImgCompressor.CompressListener, AdapterView.OnItemLongClickListener {
    private static final String TAG = "EditTeacherMienActivity";
    private static final int FINSH_CERTIFICATE = 1;
    private static final int TAKE_PICTURE = 2;
    private static final int SELECT_PICTURE = 3;
    private static final int FINSH = 4;
    private String picName;  //拍摄图片的名字
    private String path = "";
    private TextView tv_back; //
    private TextView tv_title;
    private TextView fill_add; //
    private String type;
    private String schoolname;
    private String mUrl;
    private String mType;  //为了 标识  是添加还是修改

    private int siteid; //校园介绍id
    private CommonBaseAdapter commonBaseAdapter;
    private ListView lv_edit_teacher;
    private List<ProCertificate.UListEntity> uListEntityList;
    private SelectPicPopupWindow showPopupWindow; //自定义popuowindow
    private int position;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FINSH_CERTIFICATE:
                    if (commonBaseAdapter == null) {
                        commonBaseAdapter = new CommonBaseAdapter(EditTeacherMienActivity.this, uListEntityList, R.layout.item_teacher_mien) {
                            @Override
                            public void convert(ViewHolder holder, int position) {
                                if ("1".equals(type)) {
                                    holder.setText(R.id.tv_name, "证书 :" + (position + 1));
                                    holder.setText(R.id.tv_titles, uListEntityList.get(position).title);
                                } else if ("2".equals(type)) {
                                    holder.setText(R.id.tv_name, uListEntityList.get(position).title);
                                    if (uListEntityList.get(position).content.length() > 15) {

                                        holder.setText(R.id.tv_titles, uListEntityList.get(position).content.substring(0, 13) + "...");
                                    } else {
                                        holder.setText(R.id.tv_titles, uListEntityList.get(position).content);

                                    }

                                } else if ("3".equals(type)) {
                                    holder.setText(R.id.tv_name, "学生作品 " + (position + 1));
                                    holder.setText(R.id.tv_titles, schoolname + "幼儿园学生作品");

                                }
                                Glide.with(EditTeacherMienActivity.this).load(BaseProtocol.IMG_BASE + uListEntityList.get(position).img)
                                        .error(R.drawable.video_bg).into((ImageView) holder.getView(R.id.iv_header_pic));

                            }
                        };
                        lv_edit_teacher.setAdapter(commonBaseAdapter);
                    } else {
                        commonBaseAdapter.resetList(uListEntityList);
                        commonBaseAdapter.notifyDataSetChanged();
                    }

                    break;
                case FINSH:
                    if ("change".equals(mType)) {
                        modificationKingardenName(mUrl);
                    } else if ("add".equals(mType)) {
                        modificationKingardenNameAdd(mUrl);
                    }
                    break;
            }
        }
    };

    @Override
    public void onRoot(Bundle savedInstanceState) {
        setContentView(R.layout.activity_edit_teacher_mien);

    }

    @Override
    public void initView() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        fill_add = (TextView) findViewById(R.id.fill_add);
        lv_edit_teacher = (ListView) findViewById(R.id.lv_edit_teacher);

    }

    @Override
    public void initData() {
        fill_add.setText(getString(R.string.add));
        type = getIntent().getStringExtra("type");
        schoolname = getIntent().getStringExtra("schoolname");
        siteid = getIntent().getIntExtra("siteid", 0);
        Log.i(TAG, "initData: id = " + siteid);
        if ("1".equals(type)) {
            tv_title.setText(getString(R.string.tv_certificate));
            showCertificate("1");
        } else if ("2".equals(type)) {
            tv_title.setText(getString(R.string.tv_teacher_mien));
            showCertificate("2");
        } else if ("3".equals(type)) {
            tv_title.setText(getString(R.string.tv_student_production));
            showCertificate("3");
        }
    }


    @Override
    public void initListener() {
        tv_back.setOnClickListener(this);
        fill_add.setOnClickListener(this);
        lv_edit_teacher.setOnItemClickListener(this);
        lv_edit_teacher.setOnItemLongClickListener(this);
    }

    @Override
    public void onWidgetClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.fill_add:
                Intent intent = new Intent(this, EditThreeLinkActivity.class);
                if ("1".equals(type)) {

                    intent.putExtra("type", "4");
                    intent.putExtra("siteid",siteid);
                    startActivityForResult(intent, Constant.REQUEST_CODE_ADD);

                } else if ("2".equals(type)) {
                    intent.putExtra("type", "5");
                    intent.putExtra("siteid", siteid);
                    startActivityForResult(intent, Constant.REQUEST_CODE_ADD);

                } else if ("3".equals(type)) {
                    if (uListEntityList.size() >= 2) {
                        Toast.makeText(EditTeacherMienActivity.this, "最多能添加2个学生作品!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mType = "add";
                    showPopupWindow(view);
                }
                break;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, EditThreeLinkActivity.class);
        if ("1".equals(type)) {
            intent.putExtra("type", "2");
            intent.putExtra("siteid", uListEntityList.get(position).siteid);
            intent.putExtra("uid", uListEntityList.get(position).id);
            startActivityForResult(intent, Constant.REQUEST_CODE);
        } else if ("2".equals(type)) {
            intent.putExtra("type", "3");
            intent.putExtra("siteid", uListEntityList.get(position).siteid);
            intent.putExtra("uid", uListEntityList.get(position).id);
            startActivityForResult(intent, Constant.REQUEST_CODE);

        } else if ("3".equals(type)) {
            mType = "change";
            showPopupWindow(view);
            this.position = position;

        }
    }

    //显示 弹窗
    private void showPopupWindow(View v) {

        showPopupWindow = new SelectPicPopupWindow(this, itemsOnClick);
        showPopupWindow.tv_video_babydiary_share.setText(getString(R.string.take_photo));
        showPopupWindow.tv_video_babydiary_share.setTextColor(Color.parseColor("#067DFF"));
        showPopupWindow.tv_video_babydiary_delete.setTextColor(Color.parseColor("#067DFF"));
        showPopupWindow.tv_look_big_pic.setVisibility(View.GONE);
        showPopupWindow.tv_video_babydiary_delete.setText(getString(R.string.get_phone_picture));
        showPopupWindow.tv_video_babydiary_cancle.setTextColor(Color.parseColor("#067DFF"));

        //设置layout在PopupWindow中显示的位置
        showPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_video_babydiary_share:  //拍摄
                    //先验证手机是否有sdcard
                    String status = Environment.getExternalStorageState();
                    if (status.equals(Environment.MEDIA_MOUNTED)) {
                        try {
                            File dir = new File(Environment.getExternalStorageDirectory() + "/sdcard/cache/");
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            Intent intent = new Intent();
                            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                            picName = new Date().getTime() + ".jpg";
                            Uri uri = Uri.fromFile(new File(dir, picName));
                            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(intent, TAKE_PICTURE);
                        } catch (ActivityNotFoundException e) {
                            Toast.makeText(EditTeacherMienActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
                        }
                    }
                    showPopupWindow.dismiss();

                    break;
                case R.id.tv_video_babydiary_delete: //手机中获取
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, SELECT_PICTURE);
                    showPopupWindow.dismiss();
                    break;
                case R.id.tv_video_babydiary_cancle:
                    showPopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: requestCode = " + requestCode);
        Log.i(TAG, "onActivityResult: resultCode = " + resultCode);
        if (requestCode == SELECT_PICTURE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    Uri uriPath = data.getData();

                    if (!"".equals(uriPath.getAuthority())) {
                        Cursor cursor = getContentResolver().query(uriPath,
                                new String[]{MediaStore.Images.Media.DATA},
                                null, null, null);
                        cursor.moveToFirst();
                        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    } else {
                        path = uriPath.getPath();
                    }
                    compressImage();

                }
            }
        } else if (requestCode == TAKE_PICTURE) {
            if (resultCode == RESULT_OK) {

                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sdcard/cache/" + picName;

                Bitmap bm = BitmapFactory.decodeFile(filePath);

                final File myCaptureFile = new File(filePath);
                try {
                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(myCaptureFile));
                    /* 采用压缩转档方法 */
                    bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
                    /* 调用flush()方法，更新BufferStream */
                    bos.flush();
                    /* 结束OutputStream */
                    bos.close();
                    path = myCaptureFile.getAbsolutePath();
                    compressImage();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (requestCode == Constant.REQUEST_CODE) {
            switch (resultCode) {
                case Constant.REFRESH_ADAPTER:
                    showCertificate("1");
                    break;
                case Constant.REFRESH_ADAPTER_AGAIN:
                    showCertificate("2");
                    break;
            }
        } else if (requestCode == Constant.REQUEST_CODE_ADD) {
            switch (resultCode) {
                case Constant.REFRESH_ADAPTER:
                    showCertificate("1");
                    break;
                case Constant.REFRESH_ADAPTER_AGAIN:
                    showCertificate("2");
                    break;
            }
        }
    }

    /**
     * 压缩图片
     */
    private void compressImage() {
        LGImgCompressor.getInstance(EditTeacherMienActivity.this).withListener(EditTeacherMienActivity.this).
                starCompress(Uri.fromFile(new File(path)).toString(), 600, 800, 100);

    }

    @Override
    public void onCompressStart() {
        Log.d(TAG, "onCompressStart");
    }

    @Override
    public void onCompressEnd(LGImgCompressor.CompressResult imageOutPath) {
        Log.d(TAG, "onCompressEnd outPath:" + imageOutPath.getOutPath());
        if (imageOutPath.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)//压缩失败
            return;

        File file = new File(imageOutPath.getOutPath());
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
            float imageFileSize = file.length() / 1024f;
            Log.i(TAG, "onCompressEnd:imageInfo " + "image info width:" + bitmap.getWidth() + " \nheight:" + bitmap.getHeight() +
                    " \nsize:" + imageFileSize + "kb" + "\nimagePath:" + file.getAbsolutePath());
            path = file.getAbsolutePath();
            Log.i(TAG, "onCompressEnd: imagePath_one = " + file.getAbsolutePath());
            Log.i(TAG, "onCompressEnd: imagePath_two = " + imageOutPath.getOutPath());
            Toast.makeText(EditTeacherMienActivity.this, "图片上传中,请耐心等待....", Toast.LENGTH_SHORT).show();
            showUploadPic(path);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示信息（学生作品、教师风采、资质）
     */
    private void showCertificate(String type) {
        String url = "";
        if (User.isTest) {
            url = BaseProtocol.HOST_BASE_TEST + "/synopsis/pictureList";
        } else {
            url = BaseProtocol.HOST_BASE + "/synopsis/pictureList";
        }
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addParameter("type", type);
        params.addParameter("siteid", siteid);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProCertificate proCertificate = new Gson().fromJson(result, ProCertificate.class);
                if (proCertificate.code == 0) {
                    uListEntityList = proCertificate.uList;
                    mHandler.sendEmptyMessage(FINSH_CERTIFICATE);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });

    }

    /**
     * 上传图片返回的值  (修改学生作品)
     *
     * @param mUrl
     */
    private void modificationKingardenName(String mUrl) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/pictureChange");
        params.addParameter("type", "3");
        params.addParameter("uid", uListEntityList.get(position).id);
        params.addParameter("siteid", uListEntityList.get(position).siteid);
        params.addParameter("img", mUrl);
        Log.i(TAG, "modificationKingardenName: mUrl = " + mUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {
                    Toast.makeText(EditTeacherMienActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    showCertificate("3");
//                    commonBaseAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();


            }
        });
    }

    /**
     * 上传图片返回的值  (添加学生作品)
     *
     * @param mUrl
     */
    private void modificationKingardenNameAdd(String mUrl) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/pictureAdd");
        params.addParameter("type", "3");
        params.addParameter("siteid", uListEntityList.get(position).siteid);
        params.addParameter("img", mUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {
                    Toast.makeText(EditTeacherMienActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    showCertificate("3");
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();


            }
        });
    }

    /**
     * 上传图片
     *
     * @param path 压缩后图片的路径
     */
    private void showUploadPic(String path) {

        String url = BaseProtocol.IMG_UPLOAD_HOST;
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addHeader("User-Agent", "SOHUWapRebot");
        params.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
        params.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
        params.addHeader("Connection", "keep-alive");
        params.setMultipart(true);
        params.addBodyParameter("pic", new File(path));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProUploadImg pro_class_status = new Gson().fromJson(result, ProUploadImg.class);
                Log.i(TAG, "onSuccess: code" + pro_class_status.getCode());
                if (pro_class_status != null && pro_class_status.getCode() == 0) {
                    List<String> mUrlList = pro_class_status.getUrl();
                    if (mUrlList.size() > 0) {
                        mUrl = mUrlList.get(0);
                        Log.i(TAG, "onSuccess: mUrl" + mUrl);
                    }
                    mHandler.sendEmptyMessage(FINSH);

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ex = " + ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    /**
     * 删除接口
     *
     * @param position
     * @param id
     * @param siteid
     */
    private void showDeletePublicInfo(final int position, int id, String siteid) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/pictureDel");
        params.addParameter("uid", id);
        params.addParameter("siteid",siteid);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {
                    Toast.makeText(EditTeacherMienActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    uListEntityList.remove(position);
                    commonBaseAdapter.resetList(uListEntityList);
                    commonBaseAdapter.notifyDataSetChanged();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();


            }
        });
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

        final Dialog dialog = new Dialog(this, R.style.dialog);
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.dialog_exit, null);
        dialog.setContentView(contentView);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        TextView textView1990 = (TextView) contentView.findViewById(R.id.textView1990);
        textView1990.setText("确定删除当前条目吗?");
        TextView ok = (TextView) contentView.findViewById(R.id.button_ok);
        TextView cacel = (TextView) contentView.findViewById(R.id.button_cacel);
        ok.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();

                showDeletePublicInfo(position,uListEntityList.get(position).id,uListEntityList.get(position).siteid);
            }
        });
        cacel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        return true;
    }
}

